package gui;

import br.ufpe.cin.miniJava.gui.Component;
import br.ufpe.cin.miniJava.gui.listener.ItemStateListener;

public class ComboDataListener implements ItemStateListener {

	private ComboData comboData;
	
	public ComboDataListener(ComboData cd){
		comboData = cd;
	}
	
	public void stateEvent() {	}

	public void stateEvent(Component c) {
		int dia = comboData.getDia();
		int mes = comboData.getMes();
		int ano = comboData.getAno();
		
		if(c == comboData.combo[1]){
			
			comboData.remove(comboData.combo[0]);
			
			
			
			if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(31);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				comboData.combo[0].setSelectedIndex(dia-1);
			} else if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(30);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				if(dia <= 30) comboData.combo[0].setSelectedIndex(dia-1);
			} else if(mes == 2 && bissexto(ano)){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(29);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				if(dia <= 29) comboData.combo[0].setSelectedIndex(dia-1);
			} else if(mes == 2 && !bissexto(ano)){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(28);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				if(dia <= 28) comboData.combo[0].setSelectedIndex(dia-1);
			}
		} else if ( c == comboData.combo[2] && mes == 2){
			if(!bissexto(ano)){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(28);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				if(dia <= 28) comboData.combo[0].setSelectedIndex(dia-1);
			} else if (bissexto(ano)){
				comboData.combo[0].removeAllItems();
				String[] str = comboData.getStrings(29);
				comboData.combo[0] = comboData.addComboBox(str,0,0,25,40);
				if(dia <= 29) comboData.combo[0].setSelectedIndex(dia-1);
			}
		}
		
		
		comboData.setVisible(false);
		comboData.setVisible(true);
	}

	
	public boolean bissexto(int ano){
		boolean resultado;
		resultado = false;
		
		if(ano%4 == 0) {
			resultado = true;
			if(ano%100 == 0) {
				resultado = false;
				if(ano%400 == 0) resultado = true;
			}
		}
		
		return resultado;
	}
	
}
